package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * arr
 * 1053. 交换一次的先前排列
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/9 17:44
 */
public class PrevPermOpt1 {

    public static void main(String[] args) {
        PrevPermOpt1 test = new PrevPermOpt1();

        // 1313
        int[] arr = {3, 1, 1, 3};


        // 1,7,4,6,9
//        int[] arr = {1,9,4,6,7};

        // 1,1,5
//        int[] arr = {1, 1, 5};

        int[] ints = test.prevPermOpt1(arr);
        System.out.println(Arrays.toString(ints));
    }

    public int[] prevPermOpt1(int[] arr) {
        int length = arr.length;
        for (int i = length - 2; i >= 0; i--) {
            if (arr[i] > arr[i + 1]) {
                int value = arr[i];
                int item = i + 1;
                for (int j = i + 2; j < length; j++) {
                    if (arr[j - 1] != arr[j] && arr[j] < value) {
                        item = j;
                    }
                }
                arr[i] = arr[item];
                arr[item] = value;
                break;
            }
        }
        return arr;
    }

}
